package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.AmeobaCustomerListBean
import com.hinnotek.amoeba.bean.old.AmibaSysUserAdminBean
import com.hinnotek.amoeba.bean.old.AmountAllocatedBean
import com.hinnotek.amoeba.databinding.ActivityTiOtherAmoebaInstallAddBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.AmibaInstallViewModel
import com.hinnotek.amoeba.viewmodels.ManageViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

@AndroidEntryPoint
class TIOtherAmoebaInstallAddActivity : BaseActivity<ActivityTiOtherAmoebaInstallAddBinding>(),
    View.OnClickListener {
    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var approvalUserId = 0

    val publicViewModel by viewModels<PublicInterfaceViewModel>()
    val viewModel by viewModels<AmibaInstallViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("其他阿米巴安装申请")

        setContentView(R.layout.activity_ti_other_amoeba_install_add)
    }

    override fun initVew() {
        bindingView.superButtonRequest.setOnClickListener(this)
    }

    override fun setData() {
        val orgidMe: Int = SharedPreUtils.getInteger("orgId", 0)


        publicViewModel.getAmibaCustomerListByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmeobaCustomerListBean>>() {

                override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                    val stringArrays = arrayOfNulls<String>(data.size).apply {
                        for (index in data.indices) {
                            this[index] = data[index].customerName
                        }
                    }
                    bindingView.escTiUnit.initAdapter(stringArrays)
                    bindingView.escTiUnit.setOnItemClickListener { _, _, position, _ ->
                        amibaCustomerProjectId = data[position].customerId
                    }

                    super.onDataChange(data)
                }

            })

        publicViewModel.getAmibaSysUserAdminByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.personName
                    }
                    bindingView.escTiRelatedApprover.initAdapter(strings)
                    bindingView.escTiRelatedApprover.setOnItemClickListener { _, _, position, id ->
                        approvalUserId = data[position].userId
                    }
                    super.onDataChange(data)
                }
            })



        getSysOrgAmibaList()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                111 -> bindingView.tvTiInstallDate.setText(data?.getStringExtra("date"))
                222 -> bindingView.tvTiEndDate.setText(data?.getStringExtra("date"))
            }
        }
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        when (v.id) {
            R.id.tv_ti_install_date -> IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                111
            )
            R.id.tv_ti_end_date -> IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                222
            )
            R.id.superButton_request -> {
                val orgName =
                    bindingView.escTiChooseAmoeba.editText.text.toString().trim()
                if (StringUtils.isEmpty(orgName)) {
                    ToastUtils.show(mContext, "请选择阿米巴")
                    return
                }
                val escTiUnitS = bindingView.escTiUnit.editText.text.toString().trim()
                if (StringUtils.isEmpty(escTiUnitS)) {
                    ToastUtils.show(mContext, "请选择签署单位")
                    return
                }
                val projectName = bindingView.escTiRelatedProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(projectName)) {
                    ToastUtils.show(mContext, "请选择关联项目")
                    return
                }
                val installDate = bindingView.tvTiInstallDate.text.toString().trim()
                if (StringUtils.isEmpty(installDate)) {
                    ToastUtils.show(mContext, "请选择安装时间")
                    return
                }
                val endDate = bindingView.tvTiEndDate.text.toString().trim()
                if (StringUtils.isEmpty(endDate)) {
                    ToastUtils.show(mContext, "请选择结束时间")
                    return
                }
                val installPosition = bindingView.etTiInstallLocation.text.toString().trim()
                if (StringUtils.isEmpty(installPosition)) {
                    ToastUtils.show(mContext, "请填写安装位置")
                    return
                }
                val preMoney = bindingView.etTiPreQuote.text.toString().trim()
                if (StringUtils.isEmpty(preMoney)) {
                    ToastUtils.show(mContext, "请填写预报价")
                    return
                }
                val approvalUser = bindingView.escTiRelatedApprover.editText.text.toString().trim()
                if (StringUtils.isEmpty(approvalUser)) {
                    ToastUtils.show(mContext, "请选择关联审批人")
                    return
                }
                addAmibaInstall(
                    orgId,
                    orgName,
                    customerId,
                    escTiUnitS,
                    amibaCustomerProjectId,
                    projectName,
                    installDate,
                    endDate,
                    installPosition,
                    preMoney,
                    approvalUserId,
                    approvalUser,
                    2,
                    "宁创"
                )
            }
        }
    }

    /**
     * app端添加安装申请接口
     */
    fun addAmibaInstall(
        orgId: Int, orgName: String, customerId: Int, customerName: String,
        amibaCustomerProjectId: Int, projectName: String,
        installDate: String, endDate: String, installPosition: String,
        preMoney: String, approvalUserId: Int,
        approvalUser: String, sendUserId: Int, sendUser: String
    ) {

        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String,Any>().apply {
            put("applyUserId", SharedPreUtils.getInteger("userId", 0))
            put("orgId", orgId)
            put("orgName", orgName)
            put("customerId", customerId)
            put("customerName", customerName)
            put("amibaCustomerProjectId", amibaCustomerProjectId)
            put("projectName", projectName)
            put("installDate", installDate)
            put("endDate", endDate)
            put("installPosition", installPosition)
            put("preMoney", preMoney)
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("createUser", SharedPreUtils.getString("personName"))
        }
        viewModel.addAmibaInstall(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }

    val manageViewModel by viewModels<ManageViewModel>()

    /**
     * app端获取全部阿米巴组织接口
     */
    private fun getSysOrgAmibaList(){
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        manageViewModel.getSysOrgAmibaList()
            .observe(this, object : ObserverState<MutableList<AmountAllocatedBean>>() {
                override fun onDataChange(data: MutableList<AmountAllocatedBean>) {
                    customDialog.dismiss()
                    val amountAllocatedTypeList: MutableList<String?> = ArrayList()
                    for (index in data) {
                        amountAllocatedTypeList.add(index.orgName)
                    }
                    val strings = arrayOfNulls<String>(amountAllocatedTypeList.size)
                    bindingView.escTiChooseAmoeba.initAdapter(strings)
                    bindingView.escTiChooseAmoeba.setOnItemClickListener { parent, view, position, id ->
                        orgId = data[position].orgId
                    }

                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

}